package cn.eric.framework.auth.utils;

import cn.eric.framework.auth.domain.Rule;
import org.springframework.util.AntPathMatcher;

import java.util.HashMap;
import java.util.List;

/**
 * 用于保存静态的URL和权限匹配
 */
public class EAuthRuleMap {
    private EAuthRuleMap() {
    }

    private static HashMap<String, List<String>> patternAuthorityIdsMap = new HashMap<>();

    /**
     * 用于初始化路径-权限id列表图
     *
     * @param rules 从配置文件中读取的规则列表
     */
    public static void init(List<Rule> rules) {
        for (Rule r : rules) {
            patternAuthorityIdsMap.put(r.getPattern(), r.getAuthorityIds());
        }
    }

    /**
     * 用于匹配路径
     *
     * @param path 路径
     * @return 未匹配到返回null 匹配到返回允许的权限列表
     */
    public static List<String> getNeededAuthorityIds(String path) {
        AntPathMatcher matcher = new AntPathMatcher();
        List<String> result = null;
        int length = 0;
        for (String pattern : patternAuthorityIdsMap.keySet()) {
            if (pattern.length() > length && matcher.match(pattern, path)) {
                result = patternAuthorityIdsMap.get(pattern);
            }
        }
        return result;
    }

    public static HashMap<String, List<String>> getPatternAuthorityIdsMap() {
        return patternAuthorityIdsMap;
    }
}
